package com.starblink.android.basic.user.login

import android.content.Context
import android.graphics.Color
import android.widget.TextView
import com.guadou.lib_baselib.view.span.dsl.buildSpannableString
import com.starblink.android.basic.bridge.BridgeCommand
import com.starblink.android.basic.bridge.BridgeCommandHandler
import com.starblink.android.basic.bridge.BridgeMessage
import com.starblink.android.basic.bridge.BridgeUtil
import com.starblink.android.basic.ext.isEmail
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.network.base.BaseApiClient
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.rocketreserver.FetchAccountInfoQuery
import kotlinx.coroutines.*

/**
 * 登录相关方法
 */
object LoginManager {
    const val KEY_THIRD_LOGIN_ACCOUNT = "KEY_THIRD_LOGIN_ACCOUNT"
    const val KEY_EMAIL = "KEY_EMAIL"
    const val KEY_USERNAME = "KEY_USERNAME"
    const val KEY_PERSONAL_PROFILE = "KEY_PERSONAL_PROFILE"

    /**
     * 三方登录类型
     * 10-facebook一键登录, 11-Google一键登录, 12-Apple一键登录
     */
    const val THIRD_LOGIN_GOOGLE = 11
    const val THIRD_LOGIN_FACEBOOK = 10

    /**
     * 跳转到编辑个人信息页面
     * @param pageType
     */
    fun navigationToEditPersonalInfo(context: Context) {
        context.navigationTo(RoutePage.Login.EDIT_PERSONAL_INFO)
    }


    /**
     * 登录成功后刷新Token以及用户信息
     */
    fun refreshTokenAndUserInfoAfterLoginSuccess(
        guangToken: String,
        onSuccess: () -> Unit,
        onFail: () -> Unit
    ) {
        CoroutineScope(Dispatchers.IO).launch {
            UserDataCenter.putToken(guangToken)
            val responseUserInfo = SkGqlClient.skQuery(
                FetchAccountInfoQuery(
                ),
                showDefaultLoading = true
            )
            if (responseUserInfo?.data != null && responseUserInfo.data!!.fetchAccountInfo != null) {
                //成功获取用户信息，刷新用户数据，发送通知
                UserDataCenter.setAccountInfo(responseUserInfo.data!!.fetchAccountInfo!!)
                FlowBus.boolFlowBusNotify(FlowConst.LOGIN_STATUS_CHANGE)
                //登录状态 主进程向web进程发送通知
                BridgeUtil.sendFlowBus(FlowConst.LOGIN_STATUS_CHANGE)
                MainScope().launch {
                    onSuccess()
                }
            } else {
                //获取用户信息失败，清除token
                UserDataCenter.clearToken()
                MainScope().launch {
                    onFail()
                }
            }
        }
    }

    /**
     * 刷新用户信息
     */
    fun refreshUserInfo(): Deferred<FetchAccountInfoQuery.FetchAccountInfo?> {
        return CoroutineScope(Dispatchers.IO).async {
            val responseUserInfo = SkGqlClient.skQuery(
                FetchAccountInfoQuery(
                ),
                showDefaultLoading = true
            )
            if (responseUserInfo?.data != null && responseUserInfo.data!!.fetchAccountInfo != null) {
                UserDataCenter.setAccountInfo(responseUserInfo.data!!.fetchAccountInfo!!)
                YYLogUtils.e("refreshUserInfo Success")
                return@async responseUserInfo.data!!.fetchAccountInfo!!
            } else {
                return@async null
            }
        }
    }

    /**
     * 如果用户输入的邮箱或用户名正确，返回null
     */
    fun validateUserNameOrEmail(value: String): String? {
        return if (validateUserName(value) == null || validateEmail(value) == null) null
        else "Please enter correct username or email"
    }

    /**
     * 验证用户输入邮箱，正确返回null，否则返回错误提示
     * @param linkAccount 是否用于「连接三方登录账号和Guang账号」页面
     */
    fun validateEmail(value: String, linkAccount: Boolean = false): String? {
        if (value.trim().isEmpty()) {
            return "Please provide your email"
        } else if (!value.isEmail()) {
            return if (linkAccount) "Email fail! Please type the correct email address"
            else "Please enter correct email"
        }
        return null
    }

    /**
     * 验证用户输入密码，正确返回null，否则返回错误提示
     */
    fun validatePassword(value: String): String? {
        if (value.trim().isEmpty()) {
            return "Please provide your password"
        } else if (value.trim().length < 4) {
            return "Please enter at least 4 characters"
        } else if (value.trim().length > 15) {
            return "Password is limited to 15 characters"
        }
        return null
    }

    /**
     * 验证用户输入用户名，正确返回null，否则返回错误提示
     */
    fun validateUserName(value: String): String? {
        if (value.trim().isEmpty()) {
            return "Please provide your username"
        } else if (value.trim().length < 3) {
            return "Please enter at least 3 characters"
        } else if (value.trim().length > 30) {
            return "Username is limited to 30 characters"
        } else if (!value.matches(Regex("^[A-Za-z0-9_.]+\$"))) {
            return "Please enter correct username"
        }
        return null
    }

    /**
     * TextView添加用户隐私协议
     * @param linkAccount 是否用于「连接三方登录账号和Guang账号」页面
     */
    fun setPrivacyPolicy(tv: TextView, linkAccount: Boolean = false) {
        tv.buildSpannableString {
            addText(if (linkAccount) "By linking your accounts, you agree to the " else "I agree to the ") {
                setColor(Color.parseColor("#1E293B"))
            }
            addText("Terms of Service") {
                setColor(Color.parseColor("#2563EB"))
                setClick(false) {
                    navigationTo(url = BaseApiClient.getTermsUrl())
                }
            }
            addText(" and the\n") {
                setColor(Color.parseColor("#1E293B"))
            }
            addText("Privacy Policy") {
                setColor(Color.parseColor("#2563EB"))
                setClick(false) {
                    navigationTo(url = BaseApiClient.getPrivacyUrl())
                }
            }
        }
    }

    /**
     * 登出
     */
    fun logout() {
        // 删除Token
        UserDataCenter.clearToken()
        // 退出三方登录
        if (GoogleLoginUtils.isLogin()) {
            GoogleLoginUtils.signOut()
        }
        if (FacebookLoginUtils.isLogin()) {
            FacebookLoginUtils.signOut()
        }
        // 发出事件LOGIN_STATUS_CHANGE：刷首页 刷心愿单
        FlowBus.boolFlowBusNotify(FlowConst.LOGIN_STATUS_CHANGE,bool = false)
        //登录状态 主进程向web进程发送通知
        BridgeUtil.sendFlowBus(FlowConst.LOGIN_STATUS_CHANGE)
    }
}